package org.framework.lazy.cloud.network.heartbeat.protocol;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.dns.DatagramDnsQueryDecoder;
import io.netty.handler.codec.dns.DatagramDnsResponseEncoder;

public class DnsServer {

    private final int port;

    public DnsServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        new DnsServer(53).run();
    }

    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<DatagramChannel>() {
                        @Override
                        protected void initChannel(DatagramChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new DatagramDnsQueryDecoder(),
                                    new DatagramDnsResponseEncoder(),
                                    new DnsServerHandler()
                            );
                        }
                    });

            // 绑定端口
            ChannelFuture f = b.bind(port).sync();
            System.out.println("DNS server started and listening on port " + port);
            f.channel().closeFuture().await();
        } finally {
            group.shutdownGracefully();
        }
    }
}